const getActivityUrl = "https://ali.ikenway.net:18443/api/act/findAll";
const getProductUrl = "https://ali.ikenway.net:18443/api/product/findAll";
const createActivityUrl = "https://ali.ikenway.net:18443/api/act/create";
const updateActivityUrl = "https://ali.ikenway.net:18443/api/act/update";
const deleteActivityUrl = "https://ali.ikenway.net:18443/api/act/delete";

const picUploadUrl = "https://ali.ikenway.net:18443/api/upload";


let acts = null;
let token = sessionStorage.getItem("token");
let maxOrder = 0;
let products = null;
let productSelectorOptions = [];
let actProductsGlobal = [];
let url = null;

function initActivities() {
    let tableInnerHtml = "";

    fetch(getActivityUrl, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': token
        }
    }).then(res => {

        res.json().then(json => {
            if (json.code === 200) {
                acts = json.data;

                for (let i = 0; i < acts.length; i++) {

                    let displayOrder;
                    if (acts[i].displayOrder == null) {
                        displayOrder = "";
                    } else {
                        displayOrder = acts[i].displayOrder;
                        maxOrder = maxOrder >= displayOrder ? maxOrder : displayOrder;
                    }

                    let enable = acts[i].enable ? "checked" : "";

                    tableInnerHtml += `
                        <tr class="table-row-` + i + `">
                            <td>
                                <div class="form-check">
                                    <input class="form-check-input delete-check" type="checkbox" value="` + i + `">
                                </div>
                            </td>
                            <th scope="row">` + acts[i].actId + `</th>
                            <td>
                                <label class="w-50">
                                    <input type="text" class="form-control" value="` + acts[i].actName + `">
                                </label>
                            </td>
                            <td>
                                <label class="w-50">
                                    <input type="text" class="form-control" value="` + acts[i].disCount + `">
                                </label>
                            </td>
                            <td>
                                <label class="w-50">
                                    <input type="text" class="form-control" value="` + displayOrder + `">
                                </label>
                            </td>
                            <td>
                               <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" ` + enable + ` onchange="genDisplayOrder(` + i + `)">
                               </div>
                            </td>
                            <td class="d-flex flex-row align-items-baseline mb-0">
                                <button type="button" class="btn btn-info me-3 pt-sm-1 pb-sm-1 w-2" data-bs-toggle="modal"
                                        data-bs-target="#exampleModal" data-bs-index="` + i + `">查看详情
                                </button>
                                <button type="button" class="btn btn-danger" onclick="actDelete(` + i + `)">删除</button>
                            </td>
                        </tr>
                    `;
                }

                document.getElementById("table-body").innerHTML = tableInnerHtml;
            } else if (json.code === 400) {
                alertMsg(json.msg);

                setTimeout(function () {
                    window.location.href = loginPageUrl;
                }, 2000);
            } else {
                alertMsg(json.msg);
            }
        })
    })
}

function getProducts(sortSelectorOptions = "") {

    fetch(getProductUrl, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': token
        }
    }).then(res => {
        res.json().then(json => {
            if (json.code === 200) {
                products = json.data;
            }
        });
    });
}

function initModal() {
    let modal = document.getElementById("exampleModal");

    document.getElementById("inputFile").onchange = function () {
        actImageUpload();
        document.getElementById("preview").src = url;
    }

    modal.addEventListener("show.bs.modal", function (event) {
        let index = event.relatedTarget.getAttribute('data-bs-index');

        if (index == -1) {
            initProductList([]);
            initProductOption([]);

            document.getElementById("preview").src = "img/camera.png";

            document.getElementById("save").onclick = function () {
                let act = {};
                console.log(url)
                act.imageUrl = url;
                act.actName = document.getElementById("actName").value;
                act.disCount = document.getElementById("disCount").value;
                act.displayOrder = document.getElementById("displayOrder").value == "" ? null : document.getElementById("displayOrder").value;
                act.enable = document.getElementById("status").checked;

                act.productIds = [];
                for (let i = 0; i < actProductsGlobal.length; i++) {
                    act.productIds.push(actProductsGlobal[i].productId);
                }

                actCreate(act);
                url = null;
            }
        } else {
            // 初始化活动的显示图片
            document.getElementById("preview").src = acts[index].imageUrl == null ? "img/camera.png" : acts[index].imageUrl;
            document.getElementById("status").checked = acts[index].status;

            document.getElementById("actName").value = acts[index].actName;
            document.getElementById("disCount").value = acts[index].disCount;
            document.getElementById("displayOrder").value = acts[index].displayOrder;
            document.getElementById("status").checked = acts[index].enable;

            // 初始化活动相关的商品
            actProductsGlobal = acts[index].products;
            let actProducts = acts[index].products;
            initProductList(actProducts);

            document.getElementById("save").onclick = function () {
                let act = {};
                act.imageUrl = url == null ? acts[index].imageUrl : url;
                act.actId = acts[index].actId;
                act.actName = document.getElementById("actName").value
                act.disCount = document.getElementById("disCount").value
                act.displayOrder = document.getElementById("displayOrder").value
                act.enable = document.getElementById("status").checked

                act.productIds = [];
                for (let i = 0; i < actProductsGlobal.length; i++) {
                    act.productIds.push(actProductsGlobal[i].productId);
                }

                actEdit(act);
                url = null;

            }
        }

        document.getElementById("product-add").onclick = function () {
            let selector = document.getElementById("product-add-selector");

            for (let i = 0; i < products.length; i++) {
                console.log(products[i].productId)

                if (selector.options[selector.selectedIndex].value == products[i].productId) {
                    actProductsGlobal.push(products[i]);
                    initProductList(actProductsGlobal);
                    break;
                }
            }
        }

    });

    modal.addEventListener("hidden.bs.modal", function (event) {
        document.getElementById("preview").src = "img/camera.png";
        document.getElementById("status").checked = null;

        document.getElementById("actName").value = null;
        document.getElementById("disCount").value = null;
        document.getElementById("displayOrder").value = null;
        document.getElementById("status").checked = null;

        actProductsGlobal = [];
    });


}

function initProductList(actProducts) {
    let innerHtml = "";
    for (let i = 0; i < actProducts.length; i++) {
        innerHtml += `
                    <div class="accordion-item">
                        <h2 class="accordion-header" id="heading` + i + `">
                            <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse"
                                    data-bs-target="#collapse` + i + `" aria-expanded="false" aria-controls="collapse` + i + `">
                                 ` + actProducts[i].productName + ` #` + i + `
                            </button>
                        </h2>
                        <div id="collapse` + i + `" class="accordion-collapse collapse" aria-labelledby="heading` + i + `"
                             data-bs-parent="#accordionExample">
                            <div class="accordion-body">
                                <ul class="list-group">
                                    <li class="list-group-item d-flex flex-row">
                                        <div class="w-50">
                                            折扣:
                                        </div>
                                        <div class="flex-grow-1">
                                             ` + actProducts[i].disCount + `
                                        </div>
                                    </li>
                                    <li class="list-group-item d-flex flex-row">
                                        <div class="w-50">
                                            中杯价格:
                                        </div>
                                        <div class="flex-grow-1">
                                             ` + actProducts[i].mediumPrice + `
                                        </div>
                                    </li>
                                    <li class="list-group-item d-flex flex-row">
                                        <div class="w-50">
                                            大杯价格:
                                        </div>
                                        <div class="flex-grow-1">
                                             ` + actProducts[i].largePrice + `
                                        </div>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
               `;
    }
    document.getElementById("accordionExample").innerHTML = innerHtml;

    // 选出还没有被选出来的商品并插入html代码
    initProductOption(actProducts);
}

function initProductOption(actProducts) {
    let productNotInActs = [];
    for (let i = 0; i < products.length; i++) {
        let j = 0;
        while (j < actProducts.length && actProducts[j].productId !== products[i].productId) j++;
        if (j === actProducts.length) productNotInActs.push(products[i]);
    }

    let optionInnerHtml = "";
    for (let i = 0; i < productNotInActs.length; i++) {
        optionInnerHtml += `
            <option value="` + productNotInActs[i].productId + `">` + productNotInActs[i].productName + `</option>
        `;
    }
    document.getElementById("product-add-selector").innerHTML = optionInnerHtml;
}

function actImageUpload() {
    let file = document.getElementById("inputFile").files[0];
    let data = new FormData();

    data.append("file", file);

    fetch(picUploadUrl, {
        method: 'POST',
        headers: {
            'Authorization': token
        },
        body: data
    }).then(res => {
        res.json().then(json => {
            console.log(json);

            alertMsg(json.msg);

            document.getElementById("preview").src = json.data.url;

            url = json.data.url;
        })
    });
}

function actEdit(act) {
    let productsElement = document.querySelectorAll("#product-list .product-id");

    // let data = {
    //     ""
    //     "actId": act.actId,
    //     "actName": act.actName,
    //     "disCount": act.disCount,
    //     "enable": act.status,
    //     "productIds": act.productIds
    // }

    fetch(updateActivityUrl, {
        method: 'POST',
        headers: {
            'Content-Type': "application/json",
            'Authorization': token
        },
        body: JSON.stringify(act)
    }).then(res => {
        res.json().then(json => {
            alertMsg(json.msg);
        })
    })
}

function actCreate(act) {
    fetch(createActivityUrl, {
        method: 'POST',
        headers: {
            'Content-Type': "application/json",
            'Authorization': token
        },
        body: JSON.stringify(act)
    }).then(res => {
        res.json().then(json => {
            alertMsg(json.msg);
        });
    });
}

function actDelete(index = null) {
    let data;
    let formCheck = document.querySelectorAll(".delete-check");

    if (index == null) {
        let checked = [];
        for (let i = 0; i < formCheck.length; i++) {
            if (formCheck[i].checked) {
                console.log(formCheck);
                checked.push(acts[formCheck[i].value].actId);
            }
        }
        data = {
            "actIds": checked
        }
    } else {
        data = {
            "actIds": [acts[index].actId]
        }
    }

    fetch(deleteActivityUrl, {
        method: 'POST',
        headers: {
            'Content-Type': "application/json",
            'Authorization': token
        },
        body: JSON.stringify(data)
    }).then(res => {
        res.json().then(json => {
            alertMsg(json.msg);
        });
    })
}

function genDisplayOrder(index = null) {
    if (index != null) {
        let col = document.querySelectorAll(".table-row-" + index + " .form-control");
        col[2].value = ++maxOrder;
    } else {
        document.getElementById("displayOrder").value = ++maxOrder;
    }
}